package com.fpf.client;

import com.alibaba.fastjson.JSON;
import com.fpf.config.ApiConfig;
import com.fpf.model.DeepSeekRequestModel;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.function.Consumer;
import java.util.concurrent.atomic.AtomicBoolean;

@Component
public class DeepSeekClient {
    /**
     * 请求API地址
     */
    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";
    private final OkHttpClient okHttpClient;
    private final ApiConfig apiConfig;

    @Autowired
    public DeepSeekClient(ApiConfig apiConfig, OkHttpClient okHttpClient) {
        //使用spring注入已配置客户端
        this.okHttpClient = okHttpClient;
        //使用spring注入已配置API密钥
        this.apiConfig = apiConfig;
        System.out.println("API Key: " + apiConfig.getDeepSeekApiKey()); // 添加调试信息
    }

    /**
     * 获取响应，阻塞式输出
     * @param prompt
     * @return
     * @throws IOException
     */
    public String getResponse(String prompt) throws IOException {
        // 构建请求体
        DeepSeekRequestModel.Message message = DeepSeekRequestModel.Message.builder()
                .role("user")
                .content(prompt).build();

        // 构建请求体对象
        DeepSeekRequestModel requestBody = DeepSeekRequestModel.builder()
                .model("deepseek-chat")
                .messages(Collections.singletonList(message))
                .build();

        //构建请求体json：{"messages":[{"content":"你好，DeepSeek！","role":"user"}],"model":"deepseek-chat"}
        String jsonBody = JSON.toJSONString(requestBody);
        String apiKey = apiConfig.getDeepSeekApiKey();// 使用配置文件中的API密钥

        // 创建HTTP请求
        Request request = new Request.Builder()
                .url(API_URL)
                .post(RequestBody.create(jsonBody, MediaType.get("application/json")))
                .addHeader("Authorization", "Bearer " + apiKey)
                .build();

        // 发送请求并处理响应
        try (Response response = okHttpClient.newCall(request).execute()) {
            //如果响应成功，并且返回体有内容，就输出内容，否则表示响应失败
            if (response.isSuccessful() && response.body() != null) {
                return response.body().string();
            }
            throw new IOException("Unexpected code " + response);
        }
    }


    /**
     * 新增的流式响应方法
     * @param prompt 用户输入
     * @param chunkConsumer 用于处理每个数据块的消费者
     * @param stopFlag 用于控制流式响应的中止
     * @throws IOException
     */
    public void getStreamingResponse(String prompt, Consumer<String> chunkConsumer, AtomicBoolean stopFlag) throws IOException {

        DeepSeekRequestModel.Message message = DeepSeekRequestModel.Message.builder()
                .role("user")
                .content(prompt).build();
        DeepSeekRequestModel requestBody = DeepSeekRequestModel.builder()
                .model("deepseek-reasoner")
                .messages(Collections.singletonList(message))
                .stream(true) // 开启流式输出
                .build();


        String jsonBody = JSON.toJSONString(requestBody);
        String apiKey = apiConfig.getDeepSeekApiKey();
        Request request = new Request.Builder()
                .url(API_URL)
                .post(RequestBody.create(jsonBody, MediaType.get("application/json")))
                .addHeader("Authorization", "Bearer " + apiKey)
                .addHeader("Accept", "text/event-stream") // 指定接受流式响应
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful() || response.body() == null) {
                throw new IOException("Unexpected code " + response);
            }

            /** 
             * 处理流式HTTP响应数据，解析JSON内容并分块传递给消费者。
             * 该代码块通过BufferedReader逐行读取响应流，识别并处理以"data: "开头的行。
             * 当遇到结束标志"[DONE]"时终止处理，否则解析JSON结构提取有效内容传递给回调函数。
             */
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body().byteStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    //如果该标志为true则中断流式输出
                    if (stopFlag.get()) {
                        break;
                    }
                    if (line.startsWith("data: ")) {
                        String data = line.substring(6).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(data);
                        String content = jsonObject.getJSONArray("choices")
                                .getJSONObject(0)
                                .getJSONObject("delta")
                                .getString("content");
                        if (content != null) {
                            chunkConsumer.accept(content);
                        }
                    }
                }
            }
        }
    }


}


//    public static void main(String[] args) {
//        String question = "你好，DeepSeek！";
//        try {
//            // 使用注入的API密钥
//            String response = new DeepSeekClient(new ApiConfig()).getResponse(question);
//            System.out.println(response);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }
